import { Button, Popover } from 'antd';
import React, { useState, useMemo } from 'react';
import { NodeProps, OnConnectStartParams } from 'reactflow';

import CollapsibleSection from '@/components/CollapsibleSection';
import { SvgIcon } from '@/components/icon';
import NodeTemplatesModal from '@/components/workflow/NodeTemplatesModal';
import { t } from '@/locales/i18n';
import { FlowNodeOutputTypeEnum } from '@/types/workflow/constant';
import { FlowNodeItemType } from '@/types/workflow/node';

import { ToolSourceHandle } from './render/Handle/ToolHandle';
import NodeCard from './render/NodeCard';
import RenderInput from './render/RenderInput';
import RenderOutput from './render/RenderOutput';

const NodeTools = ({ data, selected }: NodeProps<FlowNodeItemType>) => {
  const { nodeId, inputs, outputs } = data;

  const [expandedSections, setExpandedSections] = useState<Set<'output' | 'input' | 'params'>>(
    new Set(['input']),
  );

  const toggleSection = (section: 'output' | 'input' | 'params') => {
    setExpandedSections((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(section)) {
        newSet.delete(section);
      } else {
        newSet.add(section);
      }
      return newSet;
    });
  };

  const filterHiddenInputs = inputs.filter((item) => true);
  const requiredInputs = filterHiddenInputs.filter((item) => item.required);
  const optionalInputs = filterHiddenInputs.filter((item) => !item.required);

  const requireText = useMemo(() => {
    return requiredInputs
      .filter((item) => item.label !== '')
      .map((item) => t(item.label as any))
      .join('，');
  }, [requiredInputs]);

  // 获取connectParams
  const connectParams = useMemo(() => {
    return {
      nodeId,
      handleId: 'selectedTools',
      handleType: 'source',
    };
  }, [nodeId]);

  return (
    <NodeCard minW="350px" selected={selected} {...data}>
      {/* Request Configuration */}
      <div className="flex flex-col gap-3 space-y-0">
        <CollapsibleSection
          title={t('workflow.node.basic_config')}
          subtitle={`${t('workflow.node.basic_config_desc')}(${requireText})`}
          isExpanded={expandedSections.has('input')}
          onToggle={() => toggleSection('input')}
          type="input"
        >
          {requiredInputs.length > 0 && (
            <RenderInput nodeId={nodeId} flowInputList={requiredInputs} />
          )}
        </CollapsibleSection>

        {/* Parameters Configuration */}
        {optionalInputs.length > 0 && (
          <CollapsibleSection
            title={t('workflow.node.variable_config')}
            subtitle={t('workflow.node.variable_config_desc')}
            isExpanded={expandedSections.has('params')}
            onToggle={() => toggleSection('params')}
            type="params"
          >
            <div className="space-y-2">
              <RenderInput nodeId={nodeId} flowInputList={optionalInputs} />
            </div>
          </CollapsibleSection>
        )}

        {/* Output Configuration */}
        <CollapsibleSection
          title={t('workflow.node.output')}
          subtitle={t('workflow.node.output_desc')}
          isExpanded={expandedSections.has('output')}
          onToggle={() => toggleSection('output')}
          type="output"
        >
          {outputs.filter((output) => output.type !== FlowNodeOutputTypeEnum.hidden).length > 0 && (
            <div className="px-2">
              <RenderOutput nodeId={nodeId} flowOutputList={outputs} />
            </div>
          )}
        </CollapsibleSection>

        <div className="px-4 pb-3">
          <div className="relative rounded-xl bg-fill-2 py-2">
            <div className="flex items-center gap-2">
              <div className="ml-3 flex flex-col items-start gap-2">
                <span className="text-sm font-font-weight-600 text-text-5">节点选择</span>
                <span className="text-xs font-font-weight-400 text-text-4">
                  支持添加节点、插件、MCP
                </span>
              </div>

              <Popover
                className="ml-auto"
                placement="right"
                trigger="click"
                content={
                  <NodeTemplatesModal connectParams={connectParams as OnConnectStartParams} />
                }
                arrow={false}
                styles={{
                  root: {
                    paddingLeft: 30,
                  },
                }}
              >
                {' '}
                <Button type="text" icon={<SvgIcon icon="icon-add" />}>
                  添加节点
                </Button>
              </Popover>
            </div>

            <div className="absolute -right-[16px] top-1/2 -translate-y-1/2">
              <ToolSourceHandle />
            </div>
          </div>
        </div>
      </div>
    </NodeCard>
  );
};
export default React.memo(NodeTools);
